﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=TD_NOTE;
    dbFile=userLand + QString("/") + DB_FILE;
    detectDB();

    model=new QSqlTableModel(this,db);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateView();
    createMenu();
    loadLocation();
    createTray();
}

Widget::~Widget()
{
    saveLocation();

    if(db.isOpen())
        db.close();

    delete ui;
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("添加..."),this,&Widget::newItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新"),this,&Widget::updateView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("删除..."),this,&Widget::removeItem);
}

void Widget::detectDB()
{
    db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbFile);

    if(!QFile::exists(dbFile))
    {
        if(db.open())
        {
            QSqlQuery query;
            QString sql=QString(CREATE_NOTE).arg(table);
            if(!query.exec(sql))
            {
                QMessageBox::warning(this,QStringLiteral("异常情况"),
                                     QStringLiteral("无法创建本地数据库"));
                qDebug() << query.lastError().text();
            }
        }
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开本地数据库"));
    }
}

bool Widget::db_try()
{
    if(!db.isOpen())
    {
        if(!db.open())
        {
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开本地数据库"));
            return false;
        }
        else
            return true;
    }
    else
        return true;
}

void Widget::updateView()
{
    if(!db_try())
        return;

    model->setTable(table);
    model->select();
    ui->tableView->hideColumn(0);   //uid
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));    //date
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("标题")); //label
    ui->tableView->hideColumn(3);   //detail
    ui->tableView->hideColumn(4);   //addition

    clear();
}

void Widget::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        currentUid=model->data(index.sibling(index.row(),0)).toString();
        currentLabel=model->data(index.sibling(index.row(),2)).toString();
        QString detail=model->data(index.sibling(index.row(),3)).toString();
        currentAddition=model->data(index.sibling(index.row(),4)).toString();

        ui->label->setText(currentLabel);
        ui->detail->setPlainText(detail);
        ui->addition->setText(currentAddition);
    }
}

void Widget::on_btn_copy_clicked()
{
    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
        return;

    qApp->clipboard()->setText(detail);
    QMessageBox::information(this,QStringLiteral("已复制"),
                             QStringLiteral("内容已复制到剪贴板"));
}

bool Widget::addItem(const QString &label, const QString &detail, const QString &addition)
{
    if(!db_try())
        return false;

    QSqlQuery query;
    query.prepare(QString("insert into %1 (uid,date,label,detail,addition) values (?,?,?,?,?)").arg(table));
    query.addBindValue(QUuid::createUuid().toString());
    query.addBindValue(Today);
    query.addBindValue(label);
    query.addBindValue(detail);
    query.addBindValue(addition);

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

bool Widget::updateItem(const QString &label, const QString &detail, const QString &addition)
{
    if(!db_try())
        return false;

    QSqlQuery query;
    QString sql=QString("UPDATE %1 SET label='%2',detail='%3',addition='%4' where uid='%5'")
            .arg(table)
            .arg(label)
            .arg(detail)
            .arg(addition)
            .arg(currentUid);

    if(query.exec(sql))
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void Widget::clear()
{
    if(!currentUid.isEmpty())
        currentUid.clear();

    if(updateFlag)
        updateFlag=false;

    ui->label->clear();
    ui->detail->clear();
    ui->addition->clear();
}

void Widget::newItem()
{
    clear();
}

void Widget::removeItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QMessageBox::StandardButton btn=QMessageBox::warning(this,QStringLiteral("操作确认"),QStringLiteral("确定删除？无法撤销！"),
                                                         QMessageBox::Cancel | QMessageBox::Ok,
                                                         QMessageBox::Cancel );
    if(btn == QMessageBox::Ok)
    {
        QString uid=model->data(index.sibling(index.row(),0)).toString();
        QSqlQuery query;
        QString sql=QString("delete from %1 where uid='%2'").arg(table).arg(uid);
        if(query.exec(sql))
            updateView();
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("异常情况，删除失败！"));
    }
}

void Widget::on_btn_clear_clicked()
{
    clear();
}

void Widget::on_btn_save_clicked()
{
    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
        return;

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        label=detail.mid(0,8);

    QString addition=ui->addition->text().trimmed();
    if(!updateFlag)
    {
        if(!addItem(label,detail,addition))
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
        else
            updateView();
    }
    else
    {
        if(!updateItem(label,detail,addition))
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法更新数据！"));
        else
            updateView();
    }
}

void Widget::on_label_textChanged(const QString &arg1)
{
    if(currentUid.isEmpty())
        return;

    if(currentLabel != arg1)
        updateFlag=true;
}

void Widget::on_detail_textChanged()
{
    if(currentUid.isEmpty())
        return;

    updateFlag=true;
}

void Widget::on_addition_textChanged(const QString &arg1)
{
    if(currentUid.isEmpty())
        return;

    if(currentAddition != arg1)
        updateFlag=true;
}

void Widget::createTray()
{
    trayMenu=new QMenu(this);
    trayMenu->addAction(QStringLiteral("退出"),&QApplication::quit);

    tray=new QSystemTrayIcon(this);
    tray->setIcon(QIcon(":/launcher.ico"));
    tray->setContextMenu(trayMenu);
    connect(tray,&QSystemTrayIcon::activated,this,&Widget::trayActivated);
    tray->show();
}

void Widget::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
    if(reason == QSystemTrayIcon::DoubleClick)
    {
        if(isVisible())
            hide();
        else
            show();
    }
}
